package com.example.zhu95.mytimber.utils;

import android.text.TextUtils;

import com.example.zhu95.mytimber.MyApplication;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.activity.BaseActivity;
import com.example.zhu95.mytimber.entity.PlayListBean;
import com.example.zhu95.mytimber.entity.PlayQueueRecord;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.entity.SongPlayCount;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author zhu95
 * @date 2018/3/20 19:54
 */
public class DBHelper {

    public static void addPlayMusicRecord(int songid, String songids) {
        addToRecentPlaylist(songid);
        addMusicPlayCount(songid);
        recordCurrentSongs(songid, songids);
    }

    /**
     * 记录当前播放队列和歌曲id到数据库
     *
     * @param songid
     * @param songids
     */
    private static void recordCurrentSongs(int songid, String songids) {
        if (!TextUtils.isEmpty(songids)) {
            List<PlayQueueRecord> playQueueRecords = DataSupport.findAll(PlayQueueRecord.class);
            PlayQueueRecord playQueueRecord = new PlayQueueRecord();
            playQueueRecord.setCurrentId(songid);
            playQueueRecord.setSongids(songids);
            if (playQueueRecords == null || playQueueRecords.size() == 0) {
                playQueueRecord.save();
            }
            playQueueRecord.updateAll();
        }
    }

    /**
     * 记录当前播放位置到数据库
     *
     * @param currentPosition 当前播放位置
     */
    public static void recordCurrentPotision(int currentPosition) {
        PlayQueueRecord playQueueRecord = new PlayQueueRecord();
        playQueueRecord.setCurrentPosition(currentPosition);
        playQueueRecord.updateAll();
    }

    /**
     * 添加记录到播放次数记录表中
     *
     * @param songid
     */
    private static void addMusicPlayCount(int songid) {
        List<SongPlayCount> songPlayCounts = DataSupport.findAll(SongPlayCount.class);
        int index = -1;
        for (int i = 0; i < songPlayCounts.size(); i++) {
            if (songPlayCounts.get(i).getSongid() == songid) {
                index = i;
                break;
            }
        }
        SongPlayCount songPlayCount;
        if (index == -1) {
            songPlayCount = new SongPlayCount(songid);
        } else {
            songPlayCount = songPlayCounts.get(index);
        }
        int weekIndex = songPlayCount.getCurrentWeek() % SongPlayCount.Companion.getRecordWeeks();
        try {
            Field field = songPlayCount.getClass().getDeclaredField("week" + weekIndex);
            field.setAccessible(true);
            int value = field.getInt(songPlayCount) + 1;
            field.setInt(songPlayCount, value);
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
        songPlayCount.calculateScore();
        songPlayCount.save();
    }

    /**
     * 添加到最近播放列表
     *
     * @param songid
     */
    private static void addToRecentPlaylist(int songid) {
        List<PlayListBean> playLists = DataSupport.select()
                .where("isdefaultlist=? and title=?", "1", MyApplication.getContext().getString(R.string.recent_play))
                .find(PlayListBean.class);
        PlayListBean recentAddList;
        if (playLists == null || playLists.size() == 0) {
            recentAddList = new PlayListBean();
            recentAddList.setTitle(MyApplication.getContext().getString(R.string.recent_play));
            recentAddList.setDefaultList(true);
        } else {
            recentAddList = playLists.get(0);
        }
        String songIds = recentAddList.getSongIds();
        if (TextUtils.isEmpty(songIds)) {
            songIds = "" + songid;
        } else {
            boolean isContains = songIds.contains("" + songid);
            if (!isContains) {
                songIds = "" + songid + "$" + songIds;
            } else {
                int position = songIds.indexOf('$');
                //找不到说明只有一个数据，那么只有这一条数据
                if (position == -1) {
                    return;
                }
                if (Integer.parseInt(songIds.substring(0, position)) != songid) {
                    songIds = songIds.replace("$" + songid, "");
                    songIds = "" + songid + "$" + songIds;
                }
            }
        }
        recentAddList.setSongIds(songIds);
        recentAddList.save();
    }

    public static boolean add2playqueue(int songid) {
        List<PlayQueueRecord> playQueueRecords = DataSupport.findAll(PlayQueueRecord.class);
        if (playQueueRecords != null && playQueueRecords.size() > 0) {
            PlayQueueRecord playQueueRecord = playQueueRecords.get(0);
            String songids = playQueueRecord.getSongids();
            if (!songids.contains(String.valueOf(songid))) {
                if (TextUtils.isEmpty(songids)) {
                    songids = "" + songid;
                } else {
                    songids += ("$" + songid);
                }
                playQueueRecord.setSongids(songids);
                playQueueRecord.updateAll();
            }
            return true;
        }
        return false;
    }

    public static boolean deleteSong(int songid) {
        if (BaseActivity.songid == songid) {
            return false;
        }
        try {
            SongBean song = SongData.findSongByID(songid);
            //删除文件
            File file = new File(song.getPath());
            boolean delete = file.delete();
            if (!delete) {
                return false;
            }
            //把数据库中各个记录删除
            DataSupport.deleteAll(SongPlayCount.class, "songid = ?", String.valueOf(songid));
            List<PlayQueueRecord> playQueueRecords = DataSupport.findAll(PlayQueueRecord.class);
            for (PlayQueueRecord playQueueRecord : playQueueRecords) {
                String songids = playQueueRecord.getSongids();
                String s = Util.INSTANCE.removeSongidFromSongids(songid, songids);
                playQueueRecord.setSongids(s);
                playQueueRecord.save();
            }
            List<PlayListBean> playlists = DataSupport.findAll(PlayListBean.class);
            for (PlayListBean playlist : playlists) {
                String songIds = playlist.getSongIds();
                String s = Util.INSTANCE.removeSongidFromSongids(songid, songIds);
                playlist.setSongIds(s);
                playlist.save();
            }

            //将SongData中的数据删除
            SongData.songs.remove(song);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
